﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyClassServer.Net;

namespace EasyClassServer.Application.ChangePassword
{
    class Password : IApplication
    {
        public string Name => "pwd";

        public HttpResponseArgs Handle(HttpArgs args)
        {
            PasswordModel model = new PasswordModel();
            var email = args.GetPostValue()["email"].ToString();
            var emailindex = args.GetPostValue()["emailindex"].ToString();
            var verificationcode = args.GetPostValue()["verificationcode"].ToString();
            var newpwd = args.GetPostValue()["newpwd"].ToString();
            object correct_validate = Data.CacheManager.GetCache("mail" + emailindex);
            if (correct_validate == null || correct_validate.ToString() != verificationcode) 
            {
                return new HttpResponseArgs
                {
                    Code = HttpCode.Error,
                    Message = "验证码错误",
                    Data = new PasswordModel
                    {
                        Error = PasswordModel.ErrorType.VerificationCodeError
                    }
                };
            }
            try
            {
                Dictionary<string, object> info = new Dictionary<string, object>();
                info.Add("pwd", newpwd);
                model.Update("email", email, info);
                Data.CacheManager.RemoveCache("mail" + emailindex);
            }
            catch(Exception e)
            {
                return new HttpResponseArgs()
                {
                    Code = HttpCode.Error,
                    Message = e.Message,
                    Data = null
                };
            }
            return new HttpResponseArgs
            {
                Code = HttpCode.Sucsess,
                Message = "更改成功",
                Data = new PasswordModel
                {
                    Error = PasswordModel.ErrorType.Success
                }
            };
        }
    }
}
